<?php


namespace App\Http\Controllers\Weapp;


use App\Model\GoodsSku;
use App\Tool\Json;
use Illuminate\Database\Eloquent\Builder;

class Search extends Base
{


    function search()
    {


        $keyword = request()->input('keyword');


        $list = \App\Model\Goods::where('name', 'like', '%' . $keyword . '%')
            ->groupBy('name')
            ->limit(10)->get();


        return Json::code(1, 'success', $list);

    }


    /**
     *
     *  type
     *      1根据商品名称搜索
     *      2根据分类id搜索
     *
     * Create by Peter
     * 2020/01/15 11:33:58
     * Email:904801074@qq.com
     * @return array
     */
    function search_list()
    {

        $type = request()->input('type');

        $keyword = trim(request()->input('keyword'));

        \DB::connection()->enableQueryLog();

        $page = 1;

        $list=null;

        switch ($type) {


            case 1:

                $list=$this->searchByGoodsName($keyword);

                break;

            case 2:

                $list=$this->searchByCategoryId($keyword);

                break;


            default:

                $list=$this->searchByGoodsName($keyword);
                break;

        }

        //        $logs = \DB::getQueryLog();

//        $ll['log']=$logs;

        $ll= paginate($list,$page);


        $logs = \DB::getQueryLog();

        $ll['log']=$logs;

        return $ll;


    }


    /**
     * 根据名称搜索商品
     * Create by Peter
     * 2020/07/20 15:30:39
     * Email:904801074@qq.com
     * @param $keyword
     *
     * @return GoodsSku|Builder
     */
    function searchByGoodsName($keyword)
    {


//        return \App\Model\Goods::where('name','like' ,'%' . $keyword . '%')
//            ->with('goods_sku');


        return GoodsSku::whereHas('goods',function ($query)use ($keyword){


            $query->where('name','like' ,'%' . $keyword . '%');

        })->with('goods_sku_detail')->has('goods')->with('goods')->with('snapped_sku.snapped');



    }

    /**
     * 根据分类搜索商品
     * Create by Peter
     * 2020/07/20 15:30:52
     * Email:904801074@qq.com
     * @param $cid
     * @return \App\Model\Goods|Builder
     */
    function searchByCategoryId($cid){


//       return \App\Model\Goods::with('category')->whereHas('category',function ($query)use($cid){
//
////            var_dump($query);
//
//            $query->where('id',$cid);
//
//        })->with('goods_sku');

       return GoodsSku::whereHas('goods',function ($query)use ($cid){


//           $query->where('name','like' ,'%' . $keyword . '%');

           $query->where('category_id',$cid);

       })->with('goods_sku_detail')->has('goods')->with('goods')->with('snapped_sku.snapped');






    }

}
